<template>
  <div class="main-app">
    <el-card class="box-card">
      <el-form :inline="true" :model="formInline" class="form-inline">
        <el-form-item label="产生时间:">
          <div class="block">
            <el-date-picker v-model="formInline.transportTime" type="daterange" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" style="width: 100%;" format="yyyy 年 MM 月 dd 日"
            />
          </div>
        </el-form-item>
        <el-form-item label="废物名称:">
          <el-input v-model="formInline.name" clearable />
        </el-form-item>
        <el-form-item label="废物代码:">
          <el-input v-model="formInline.codeContent" clearable />
        </el-form-item>
        <!--      <el-form-item label="废物类别:">
          <el-input v-model="formInline.waste" clearable />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh-right" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="show-result">

      <!-- 加载动态菜单 -->
      <el-form :inline="true" class="form-inline">
        <el-form-item v-for="item in toolbtn" :key="item.id">
          <el-button type="primary" :icon="item.meta.icon" @click="showViews(item.name)">
            {{ item.meta.title }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <div> 当前页统计： 容器总数量：{{ summaryWastCount }} 个 | 废物总重量：
            {{ summaryWastWeight }} 吨
          </div>
        </el-form-item>
      </el-form>

      <!-- <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" icon="el-icon-sold-out" @click="view">
            次生废物入库
          </el-button>
        </el-form-item>
        <el-form-item>
          <div> 当前页统计： 容器总数量：{{ summaryWastCount }} 个 | 废物总重量：
            {{ summaryWastWeight }} 吨
          </div>
        </el-form-item>
      </el-form> -->

      <div class="result" style="margin-top: -40px;">
        <div class="tool">
          <el-button type="primary" size="mini" icon="el-icon-notebook-1" :disabled="deleteDisabled" plain @click="exportData" />
          <el-button type="primary" size="mini" icon="el-icon-printer" plain @click="printData" />
        </div>
        <el-table id="table" ref="multipleTable" v-loading="loading" border :data="tableData" tooltip-effect="dark"
                  style="width: 100%" @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />

          <!-- <el-table-column prop="areaNumber" label="行政区域代码" width="110" /> -->
          <el-table-column prop="name" label="废物名称" width="100" />
          <el-table-column prop="number" label="数字识别码" width="100" />
          <el-table-column prop="categoryContent" label="废物类别" width="80" />
          <el-table-column prop="codeId" label="废物代码" width="100" />

          <!-- <el-table-column prop="hazardousSubstancesName" label="危险废物" width="100" /> -->
          <el-table-column prop="characteristicContent" label="危险特性" width="80" />
          <!-- <el-table-column prop="physicalProperties" label="废物形态" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">
                {{ scope.row.physicalProperties | parsePhysicalProperties }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="physicalProperties" label="废物形态" width="100">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.physicalPropertiesColor ">
                {{ scope.row.physicalPropertiesName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="hwUtilizeDisposalMethod" label="利用处置方式" width="110" />
          <el-table-column prop="pos" label="贮存设施" width="100" />
          <!-- <el-table-column prop="disposalFacilitiesType" label="设施类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">
                {{ scope.row.disposalFacilitiesType | parseWarehouseCategory }}
              </el-tag>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="disposalFacilitiesType" label="设施类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.disposalFacilitiesTypeColor ">
                {{ scope.row.disposalFacilitiesTypeName }}
              </el-tag>
            </template>
          </el-table-column> -->
          <!-- <el-table-column prop="wareHouseLocationName" label="贮存库位" width="100" /> -->
          <!-- <el-table-column prop="containerCategory" label="包装类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark">
                {{ scope.row.containerCategory | parseContainerType }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="containerCategory" label="包装类型" width="80">
            <template slot-scope="scope">
              <el-tag style="width: 100%; text-align: center;" effect="dark" :class="'bg-'+scope.row.containerCategoryColor ">
                {{ scope.row.containerCategoryName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="packagingNumber" label="包装数量" width="100" />
          <el-table-column prop="produceInBatchNumber" label="入库批次号" width="100" />
          <el-table-column prop="inOutAmount" label="入库量 (吨)" width="100" />
          <el-table-column prop="createTime" label="产生入库时间" width="110">
            <template slot-scope="scope">
              {{ scope.row.createTime | parseDate }}
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="操作人" width="100" />
          <el-table-column prop="wpcName" label="产废单位" width="200" />

          <el-table-column prop="describe" label="备注" width="100" />

        </el-table>
        <div class="page">
          <el-pagination background :current-page.sync="currentPage" layout="total,prev, pager, next,sizes" :total="total"
                         :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" @current-change="handleCurrentChange" @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>

    <div class="dialog_diy">
      <el-dialog :visible.sync="dialogVisible" width="70%" style="margin-top: -50px;" @close="cancel">
        <div slot="title" style="background:#1890FF;color: white;">
          <div style="padding:15px 20px;">新增废物入库</div>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-row style="margin-top: 10px">
            <el-col :span="12">
              <el-form-item label="废物名称:" required prop="wastName">
                <el-input v-model="form.wastName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="废物类别:">
                <el-input v-model="form.wastObj.categoryContent" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="废物代码:">
                <el-input v-model="form.wastObj.codeId" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="危险特性:">
                <el-input v-model="form.wastObj.characteristicContent" disabled style="width: 90%;" />
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <!-- <el-form-item label="容器类型:">
                <el-input v-model="form.wastObj.containerCategory" disabled style="width: 90%;" />
              </el-form-item> -->
              <el-form-item label="危害成分:">
                <el-input v-model="form.wastObj.hazardousSubstancesName" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="废物形态:">
                <el-input v-model="form.wastObj.physicalProperties" disabled style="width: 90%;" />
              </el-form-item>
              <el-form-item label="来源及生产工序:">
                <el-input v-model="form.wastObj.processContent" disabled style="width: 90%;" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">入库信息</el-divider>
          <el-row style="margin-top: 10px">

            <el-col :span="12">
              <el-form-item label="存放仓库:">
                <el-select v-model="form.wareHouseId" placeholder="请选择" style="width: 90%;" @change="changeWastHouse">
                  <el-option v-for="item in houseList" :key="item.id" :label="item.name" :value="item.id" />
                  <!-- <el-option label="未填写" value="" /> -->
                </el-select>
              </el-form-item>
              <el-form-item label="入库量 (吨):" required prop="inAmount">
                <el-input v-model="form.inAmount" type="number" style="width: 90%;" @blur="changeInAmount" />
              </el-form-item>
              <el-form-item label="容器类别:" prop="containerType">
                <el-radio-group v-model="containerType" :disabled="isView">
                  <el-radio v-for="(item, index) in containerOptions" :key="index" :label="item.value">{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="存放库位:">
                <el-select v-model="form.wareHouseLocationId" placeholder="请选择" style="width: 90%;" @change="changeWastHouseLocation">
                  <el-option v-for="item in housePosList" :key="item.id" :label="item.name" :value="item.id" />
                  <!-- <el-option label="未填写" value="" /> -->
                </el-select>
              </el-form-item>
              <el-form-item label="入库批次号:" required prop="batchLabel">
                <el-input v-model="form.batchLabel" style="width: 90%;" />
              </el-form-item>
              <el-form-item label="危险标语:" prop="termId">
                <el-select v-model="form.termId" filterable placeholder="请选择" clearable :disabled="isView" style="width: 90%"
                           @change="termContentChange"
                >
                  <el-option v-for="item in termContentOptions" :key="item.id" :label="item.content" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-form-item label="禁忌与应急措施:" prop="safetyPrecautions">
              <el-select v-model="form.safetyPrecautionsId" filterable placeholder="请选择" clearable :disabled="isView"
                         style="width: 95%" @change="safetyPrecautionsChange"
              >
                <el-option v-for="item in safetyPrecautionsOptions" :key="item.id" :label="item.content" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-row>

          <el-row>
            <el-form-item label="备注:">
              <el-input v-model="form.describe" type="textarea" style="width:95%;" />
            </el-form-item>
          </el-row>

          <el-row style="margin-top: 40px; text-align: center">
            <el-form :inline="true" class="form-inline">
              <el-form-item>
                <el-button type="primary" :loading="isInstoreing" @click="selectedWasteType">选择废物类型</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="success" :loading="isInstoreing" @click="inStore('10')">入库并打印标签</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="danger" :loading="isInstoreing" @click="inStore('0')">确认入库</el-button>
              </el-form-item>
              <el-form-item>
                <el-button @click="cancel">取 消</el-button>
              </el-form-item>
            </el-form>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// Table组件相关逻辑，需要引用
import {
  pageMixin
} from "../../../mixins/index";
import {
  transportFromState,
  ContainerType,
  PhysicalProperties,
  WarehouseCategory
} from "../../../utils/resource.js";

import {
  getInOutStoreRecordList,
  getWareHouseList,
  getPosListByWareHouseId,

  addInStoreOfSecondWast
} from '../../../api/warehouse.js';
import {
  // getWasteTypeList,
  // getWasteCodeList,
  // getSourceProcessList,
  // addWasteInformation,
  // getWasteInformationById,
  getWasteTermList,
  GetAllHWSafetyprecautionsList,
  // GetWasteInformationListForProductAsync,
  // getDictionaryListByType
} from "../../../api/system";
import {
  parseTime,
  getFloat,
  generateTimeReqestNumber,
  createCode,
  getInOutCode
} from '../../../utils/index.js';
export default {
  filters: {
    parseDate(value) {
      if (value) {
        return value.replace("T", " ");
      }
    },
    parseContainerType(value) {
      if (value) {
        var obj = ContainerType.find((p) => p.value === `${value}`);
        var label = "";
        if (obj) {
          label = obj.label;
        }
        return label;
      }
    },
    parsePhysicalProperties(value) {
      if (value) {
        var obj = PhysicalProperties.find((p) => p.value === `${value}`);
        var label = "";
        if (obj) {
          label = obj.label;
        }
        return label;
      }
    },
    parseWarehouseCategory(value) {
      if (value) {
        var obj = WarehouseCategory.find((p) => p.value === `${value}`);
        var label = "";
        if (obj) {
          label = obj.label;
        }
        return label;
      }
    },

  },

  mixins: [pageMixin],
  data() {
    return {
      isInstoreing: false,
       containerType:'0',

      transportFromStateOption: transportFromState,
      formInline: {
        transportTime: ["", ""],
        name: "",
        codeContent: "",
      },

      form: {
        id: "",
        wastObj: {},
        wastName: "",
        inAmount: 0,
        describe: "",
        batchLabel: "",
        disposalFacilitiesType: ""
      },
      dialogVisible: false,

      containerOptions: ContainerType,
      termContentOptions: [],
      safetyPrecautionsOptions: [],

      houseList: [],
      housePosList: [],

      rules: {
        inAmount: [{
          required: true,
          message: "请填写入库量",
          trigger: "blur"
        }],
        batchLabel: [{
          required: true,
          message: "请填写入库批次号",
          trigger: "blur"
        }],

        wastName: [{
          required: true,
          message: "请选择需要入库的危险废物",
          trigger: "blur"
        }],

        wareHouseId: [{
          required: true,
          message: "请选择贮存仓库",
          trigger: "change"
        }],
        wareHouseLocationId: [{
          required: true,
          message: "请选择贮存库位",
          trigger: "change"
        }],
      },
      toolbtn: [] // 列表顶部按钮
    };
  },
  async created() {
    var tempInhouseObjInfo = JSON.parse(localStorage.getItem('tempInhouseObjInfo'));
    if (tempInhouseObjInfo) {
      this.form = tempInhouseObjInfo;
      if (this.form.wastObj) {
        var obj = WarehouseCategory.find((p) => p.value === `${this.form.wastObj.containerCategory}`);
        if (obj) {
          this.form.wastObj.containerCategory = obj.label
        }

        //  var obj2 = PhysicalProperties.find((p) => p.value === `${ this.form.wastObj.physicalProperties}`);
        //  if (obj) {
        //    this.form.wastObj.physicalProperties=obj2.label
        //  }
      }
      this.dialogVisible = true;
    }
    await this.init();
  },
  methods: {
    // 列表顶部功能按钮点击事件
    showViews(action) {
      // console.log(action);
      switch (action) {
        case '次生废物入库':
          this.view();
          break;
      }
    },
    termContentChange(e) {
      var _this = this;
      var obj = _this.termContentOptions.find(item => {
        return item.id === e
      })
      if (obj) {
        _this.form.termContent = obj.content;
        _this.form.termId = obj.id;
      }
    },
    safetyPrecautionsChange(e) {
      var _this = this;

      var obj = _this.safetyPrecautionsOptions.find(item => {
        return item.id === e
      })
      if (obj) {
        _this.form.safetyPrecautions = obj.content;
        _this.form.safetyPrecautionsId = obj.id;
      }
    },
    async init() {
      this.tableData = [];
      this.loading = true;
      var searchDatas = {
        limit: this.pageSize,
        page: this.currentPage,
        searchParam: JSON.stringify({
          "OperateType": "10",
          "InOutType": "10",
          "Name": this.formInline.name,
          "CodeContent": this.formInline.codeContent,
          "StartTime": parseTime(this.formInline.transportTime[0]) === null ? "" : parseTime(this.formInline
            .transportTime[0]).substring(0, 10),
          "EndTime": parseTime(this.formInline.transportTime[1]) === null ? "" : parseTime(this.formInline
            .transportTime[1]).substring(0, 10)
        })
      };
        // 并行获取数据
      Promise.all([await getInOutStoreRecordList(searchDatas),
        await getWareHouseList(),
        await getWasteTermList(),
        await GetAllHWSafetyprecautionsList(searchDatas)
      ])
        .then((result) => {
          this.tableData = result[0].data;
          this.tableData.forEach(item => {


            item.pos = (item.wareHouseName === null ? "" : item.wareHouseName + "-") + (item
              .wareHouseLocationName === null ? "" : item.wareHouseLocationName)

            var obj = PhysicalProperties.find((p) => p.value === `${item.physicalProperties}`);
            if (obj) {
              item.physicalPropertiesName = obj.label;
              item.physicalPropertiesColor = obj.color;
            } else {
              item.physicalPropertiesName = "无数据";
              item.physicalPropertiesColor = "red";
            }

            var obj2 = WarehouseCategory.find((p) => p.value === `${item.disposalFacilitiesType}`);
            if (obj2) {
              item.disposalFacilitiesTypeName = obj2.label;
              item.disposalFacilitiesTypeColor = obj2.color;
            } else {
              item.disposalFacilitiesTypeName = "无数据";
              item.disposalFacilitiesTypeColor = "red";
            }

            var obj3 = ContainerType.find((p) => p.value === `${item.containerCategory}`);
            if (obj3) {
              item.containerCategoryName = obj3.label;
              item.containerCategoryColor = obj3.color;
            } else {
              item.containerCategoryName = "无数据";
              item.containerCategoryColor = "red";
            }
          });

          this.total = result[0].count;
          this.undataSummaryData(result[0].data);

          this.termContentOptions = result[2].data;
          this.safetyPrecautionsOptions = result[3].data;

          this.houseList = result[1].data;
          if (this.houseList) {
            if (!this.form.wareHouseId && this.houseList.length !== 0) {
              this.form.wareHouseId = this.houseList[0].id;
              this.form.wareHouseName = this.houseList.find((p) => p.id === `${this.houseList[0].id}`)
                .name;
            }
          }
        })
        .then(async() => {
          if (this.form.wareHouseId) {
            await this.getPosListByWareHouseId(this.form.wareHouseId);
          }
        })
      this.loading = false;
 this.containerType = "0";
      // 初始化按钮数据
      this.toolbtn = JSON.parse(localStorage.getItem('次生废物入库台账'));
      // console.log(this.toolbtn);

      // await this.getWareHouseList();
    },
    undataSummaryData(tableDataList) {
      this.summaryWastCount = 0;
      this.summaryWastWeight = 0;

      tableDataList.forEach(item => {
        if (item.inAmount < 0) {
          item.inAmount = 0
        }
        this.summaryWastWeight += item.inOutAmount;
        this.summaryWastCount += 1;
      })
      this.summaryWastWeight = getFloat(this.summaryWastWeight, 5)
    },
    changeInAmount(val) {
      if (this.form.inAmount <= 0) {
        this.form.inAmount = 0;
      }
    },

    async changeWastHouse(val) {
      this.form.wareHouseId = val;
      var obj = this.houseList.find((p) => p.id === `${val}`);
      if (obj) {
        this.form.wareHouseName = obj.name;
        this.form.disposalFacilitiesType = obj.type;
      } else {
        this.form.wareHouseName = "";
        this.form.disposalFacilitiesType = "";
      }
      await this.getPosListByWareHouseId(val);
    },

    async changeWastHouseLocation(val) {
      this.form.wareHouseLocationId = val;
      var obj = this.housePosList.find((p) => p.id === `${val}`);
      if (obj) {
        this.form.wareHouseLocationName = obj.name;
      } else {
        this.form.wareHouseLocationName = ""
      }
    },

    async getPosListByWareHouseId(wareHouseId) {
      const {
        data
      } = await getPosListByWareHouseId(wareHouseId)
      this.housePosList = [];
      this.housePosList = data;
      if (this.housePosList) {
        if (this.housePosList.length !== 0) {
          this.form.wareHouseLocationId = this.housePosList[0].id;
          this.form.wareHouseLocationName = this.housePosList.find((p) => p.id === `${this.housePosList[0].id}`)
            .name;
        } else {
          this.form.wareHouseLocationId = "";
          this.form.wareHouseLocationName = "";
        }
      } else {
        this.form.wareHouseLocationId = "";
        this.form.wareHouseLocationName = "";
      }
    },

    // 关闭dialog时候触发
    closeDialog() {
      // 清除转运申请详情存在localstroage的临时表单内容
      this.resectInfo();
    },
    cancel() {
      this.$router.push("/warehouse/inhouse_Secondary");
      this.dialogVisible = false;
      // 清除转运申请详情存在localstroage的临时表单内容
      this.resectInfo();
    },
    resectInfo() {
      localStorage.removeItem('tempInhouseObjInfo');
      this.form = {
        id: "",
        wastObj: {},
        wastName: "",
        inAmount: 0,
        describe: "",
        batchLabel: "RK" + getInOutCode(),
        disposalFacilitiesType: ""
      }
    },
    downPDF() {
      this.$message.error('功能等待完成');
    },
    view() {
      if (this.$refs['form']) {
        // 重置表单验证
        this.$refs.form.resetFields()
      }
      this.resectInfo();
      this.dialogVisible = true;
    },
    selectedWasteType() {
      localStorage.setItem('tempInhouseObjInfo', JSON.stringify(this.form));
      this.$router.push("/warehouse/inhouse_Secondary/index_WastTypeList");
    },
    async inStore(type) {
      // 校验必填项
      this.$refs["form"].validate(async(valid) => {
        if (valid) { // 校验成功
          if (getFloat(this.form.inAmount, 5) <= 0) {
            this.$message.error('入库重量需大于0');
            return;
          }
          let data = {};
          let message = "";
          data = {
            HazardousWasteId: this.form.wastObj.id,
            HazardousWasteNumber: generateTimeReqestNumber() + createCode().toString(),
            WareHouseId: this.form.wareHouseId,
            WareHouseName: this.form.wareHouseName,
            WareHouseLocationId: this.form.wareHouseLocationId,
            WareHouseLocationName: this.form.wareHouseLocationName,
            InAmount: getFloat(this.form.inAmount, 5),
            Remarks: this.form.describe,
            DisposalFacilitiesType: this.form.disposalFacilitiesType,
            "BatchLabel": this.form.batchLabel,
            DisposalMethod: "贮存",
            "InOutType": "10", // (出入库类型  10: 次生入库 20: 产生台账  30: 接收入库 40: 转移出库 50: 委外转移出库)

            // 新增参数
            containerCategory: this.containerType,
            TermId: this.form.termId,
            TermContent: this.form.termContent,
            SafetyPrecautionsId: this.form.safetyPrecautionsId,
            SafetyPrecautions: this.form.safetyPrecautions,
          };

          this.isInstoreing = true;

          message = "废物入库成功";
          const {
            success,
            msg
          } = await addInStoreOfSecondWast(data);

          if (success) {
            await this.init();
            this.isInstoreing = false;
            this.$notify({
              title: "成功",
              message: message,
              type: "success",
              duration: 3000,
            });
          } else {
            this.isInstoreing = false;
            this.$notify.error({
              title: "失败",
              message: msg,
              duration: 3000,
            });
          }

          if (type === '10') { // 保存并打印
            // todu

          }
          // 清除转运申请详情存在localstroage的临时表单内容
          localStorage.removeItem('tempInhouseObjInfo');
          this.dialogVisible = false;
          await this.init();
        }
      });
    },

    async reset() {
      this.formInline = {
        transportTime: ["", ""],
        number: "",
        status: "",
        characteristic: "",
      };
      await this.init();
    },
  },
};
</script>

<style lang="scss" scoped>
  .result {
    margin-top: 10px;
  }

  .page {
    margin-top: 20px;
    text-align: right;
    margin-bottom: 40px;
  }

  .show-result {
    margin-top: 10px;
  }

  .dialog_diy {
    ::v-deep .el-dialog__wrapper {

      // eslint-disable-line
      .el-dialog {

        .el-dialog__body {
          padding: 0px;
        }

        .el-dialog__header {
          padding: 0px;
        }

        .el-dialog__headerbtn {
          top: 5px;
          right: 5px;
          padding-top: 10px;
        }

        .el-dialog__headerbtn .el-dialog__close {
          color: #fff;
          height: 30px;
          width: 35px;
        }

        .el-dialog__headerbtn .el-dialog__close:hover {
          color: gray;
        }
      }
    }
  }
</style>
